package com.burst.reptile.modular.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.burst.reptile.common.constant.Constants;
import com.burst.reptile.common.constant.HttpStatus;
import com.burst.reptile.common.constant.UserConstants;
import com.burst.reptile.common.exception.CustomException;
import com.burst.reptile.common.exception.user.CaptchaException;
import com.burst.reptile.common.exception.user.CaptchaExpireException;
import com.burst.reptile.common.utils.SecurityUtils;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.framework.aspectj.lang.annotation.DataScope;
import com.burst.reptile.framework.redis.RedisCache;
import com.burst.reptile.framework.security.SignupBody;
import com.burst.reptile.modular.api.form.UserInfoForm;
import com.burst.reptile.modular.api.form.UserPwdForm;
import com.burst.reptile.modular.system.entity.SysPost;
import com.burst.reptile.modular.system.entity.SysRole;
import com.burst.reptile.modular.system.entity.SysUser;
import com.burst.reptile.modular.system.entity.SysUserPost;
import com.burst.reptile.modular.system.entity.SysUserRole;
import com.burst.reptile.modular.system.mapper.SysPostMapper;
import com.burst.reptile.modular.system.mapper.SysRoleMapper;
import com.burst.reptile.modular.system.mapper.SysUserMapper;
import com.burst.reptile.modular.system.mapper.SysUserPostMapper;
import com.burst.reptile.modular.system.mapper.SysUserRoleMapper;
import com.burst.reptile.modular.system.service.ISysConfigService;
import com.burst.reptile.modular.system.service.ISysUserService;
import com.burst.reptile.modular.zp.entity.ZpFormat;
import com.burst.reptile.modular.zp.form.NewForgot;
import com.burst.reptile.modular.zp.mapper.ZpFormatMapper;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author wujin
 * @since 2020-05-21
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

	private final SysUserPostMapper userPostMapper;

	private final SysUserRoleMapper userRoleMapper;

	private final ISysConfigService configService;

	private final SysRoleMapper roleMapper;
	
	private final SysPostMapper postMapper;
	
	private final RedisCache redisCache;
	
	private final ZpFormatMapper formatMapper;
	
	@Override
	public SysUser selectUserByUserName(String userName) {
		return this.baseMapper.selectUserByUserName(userName);
	}

	@Override
	@DataScope(deptAlias = "d", userAlias = "u")
	public Page<SysUser> selectUserList(Page<SysUser> page, SysUser user) {
		return this.baseMapper.selectUserList(page, user);
	}

	@Override
	public String checkUserNameUnique(String userName) {
		int count = this.count(new QueryWrapper<SysUser>().eq("user_name", userName));
		if (count > 0) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}

	@Override
	public String checkPhoneUnique(SysUser user) {
		Long userId = ToolUtil.isEmpty(user.getUserId()) ? -1L : user.getUserId();
		SysUser info = this.baseMapper.selectOne(
				new QueryWrapper<SysUser>().select("user_id", "phonenumber").eq("phonenumber", user.getPhonenumber()));
		if (ToolUtil.isNotEmpty(info) && info.getUserId().longValue() != userId.longValue()) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}

	@Override
	public String checkEmailUnique(SysUser user) {
		Long userId = ToolUtil.isEmpty(user.getUserId()) ? -1L : user.getUserId();
		SysUser info = this.baseMapper
				.selectOne(new QueryWrapper<SysUser>().select("user_id", "email").eq("email", user.getEmail()));
		if (ToolUtil.isNotEmpty(info) && info.getUserId().longValue() != userId.longValue()) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}

	@Override
	@Transactional
	public int insertUser(SysUser user) {
		// 新增用户信息
		int rows = this.baseMapper.insert(user);
		// 新增用户岗位关联
		insertUserPost(user);
		// 新增用户与角色管理
		insertUserRole(user);
		return rows;
	}

	/**
	 * 新增用户岗位信息
	 * 
	 * @param user 用户对象
	 */
	public void insertUserPost(SysUser user) {
		Long[] posts = user.getPostIds();
		if (ToolUtil.isNotEmpty(posts)) {
			// 新增用户与岗位管理
			List<SysUserPost> list = new ArrayList<SysUserPost>();
			for (Long postId : posts) {
				SysUserPost up = new SysUserPost();
				up.setUserId(user.getUserId());
				up.setPostId(postId);
				list.add(up);
			}
			if (list.size() > 0) {
				userPostMapper.batchUserPost(list);
			}
		}
	}

	/**
	 * 新增用户角色信息
	 * 
	 * @param user 用户对象
	 */
	public void insertUserRole(SysUser user) {
		Long[] roles = user.getRoleIds();
		if (ToolUtil.isNotEmpty(roles)) {
			// 新增用户与角色管理
			List<SysUserRole> list = new ArrayList<SysUserRole>();
			for (Long roleId : roles) {
				SysUserRole ur = new SysUserRole();
				ur.setUserId(user.getUserId());
				ur.setRoleId(roleId);
				list.add(ur);
			}
			if (list.size() > 0) {
				userRoleMapper.batchUserRole(list);
			}
		}
	}

	@Override
	public void checkUserAllowed(SysUser user) {
		if (ToolUtil.isNotEmpty(user.getUserId()) && user.isAdmin()) {
			throw new CustomException("不允许操作超级管理员用户");
		}
	}

	@Override
	@Transactional
	public int updateUser(SysUser user) {
		Long userId = user.getUserId();
		// 删除用户与角色关联
		userRoleMapper.delete(new UpdateWrapper<SysUserRole>().eq("user_id", userId));
		// 新增用户与角色管理
		insertUserRole(user);
		// 删除用户与岗位关联
		userPostMapper.delete(new UpdateWrapper<SysUserPost>().eq("user_id", userId));
		// 新增用户与岗位管理
		insertUserPost(user);
		return baseMapper.updateById(user);
	}

	@Override
	public int deleteUserByIds(Long[] userIds) {
		for (Long userId : userIds) {
			SysUser sysUser = new SysUser();
			sysUser.setUserId(userId);
			checkUserAllowed(sysUser);
		}
		return this.baseMapper.deleteUserByIds(userIds);
	}

	@Override
	public int resetPwd(SysUser user) {
		return this.baseMapper.updateById(user);
	}

	@Override
	public int updateUserStatus(SysUser user) {
		boolean update = this.update(
				new UpdateWrapper<SysUser>().set("user_status", user.getUserStatus()).eq("user_id", user.getUserId()));
		return update ? 1 : 0;
	}

	@Override
	@DataScope(deptAlias = "d", userAlias = "u")
	public List<SysUser> selectUserList(SysUser user) {
		return this.baseMapper.selectUserList(user);
	}

	@Override
	public String importUser(List<SysUser> userList, boolean isUpdateSupport) {
		if (ToolUtil.isEmpty(userList) || userList.size() == 0) {
			throw new CustomException("导入用户数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		String password = configService.selectConfigByKey("sysUserInitPassword");
		for (SysUser user : userList) {
			try {
				// 验证是否存在这个用户
				SysUser u = this.baseMapper.selectUserByUserName(user.getUserName());
				if (ToolUtil.isEmpty(u)) {
					user.setPassword(SecurityUtils.encryptPassword(password));
					this.insertUser(user);
					successNum++;
					successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
				} else if (isUpdateSupport) {
					this.updateUser(user);
					successNum++;
					successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
				} else {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
				}
			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
				failureMsg.append(msg + e.getMessage());
				log.error(msg, e);
			}
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new CustomException(failureMsg.toString());
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}

	@Override
	public String selectUserRoleGroup(String userName) {
		List<SysRole> list = roleMapper.selectRolesByUserName(userName);
		StringBuffer idsStr = new StringBuffer();
		for (SysRole role : list) {
			idsStr.append(role.getRoleName()).append(",");
		}
		if (StrUtil.isNotEmpty(idsStr.toString())) {
			return idsStr.substring(0, idsStr.length() - 1);
		}
		return idsStr.toString();
	}

	@Override
	public String selectUserPostGroup(String userName) {
		List<SysPost> list = postMapper.selectPostsByUserName(userName);
		StringBuffer idsStr = new StringBuffer();
		for (SysPost post : list) {
			idsStr.append(post.getPostName()).append(",");
		}
		if (StrUtil.isNotEmpty(idsStr.toString())) {
			return idsStr.substring(0, idsStr.length() - 1);
		}
		return idsStr.toString();
	}

	@Override
	public int updateUserProfile(SysUser user) {
		return this.baseMapper.updateById(user);
	}

	@Override
	public int resetUserPwd(String userName, String password) {
		SysUser user = new SysUser();
		user.setPassword(password);
		return this.baseMapper.update(user, new UpdateWrapper<SysUser>().eq("user_name", userName));
	}

	@Override
	public boolean updateUserAvatar(String userName, String avatar) {
		SysUser user = new SysUser();
		user.setAvatar(avatar);
		return this.baseMapper.update(user, new UpdateWrapper<SysUser>().eq("user_name", userName)) > 0;
	}

	@Override
	public Page<SysUser> search(int pageNum, int limit, String keyword, List<String> ik) {
		Page<SysUser> page = new Page<>(pageNum, limit);
		if(StrUtil.isNotEmpty(keyword)) {
			QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
			queryWrapper.select("user_id", "nick_name", "avatar", "user_status", "user_type");
			if(SecurityUtils.isLogin()) {
				Long userId = SecurityUtils.getLoginUserId();
				queryWrapper.ne("user_id", userId);
			}
			queryWrapper.eq("user_status", 0).eq("user_type", "11");
			if(ToolUtil.isNotEmpty(ik)) {
				for (String string : ik) {
					queryWrapper.like("nick_name", string).or().like("label", string).or();
				}
			}else {
				queryWrapper.like("nick_name", keyword).or().like("label", keyword);
			}
			return this.page(page, queryWrapper);
		}
		return new Page<>(pageNum, limit);
	}

	@Override
	@Transactional
	public void signup(SignupBody signupBody) {
		String code = signupBody.getCode();
		String verifyKey = Constants.CAPTCHA_CODE_KEY + signupBody.getUuid();
		String captcha = redisCache.getCacheObject(verifyKey);
		redisCache.deleteObject(verifyKey);
		if (captcha == null) {
			throw new CaptchaExpireException();
		}
		if (!StrUtil.equalsIgnoreCase(code, captcha)) {
			throw new CaptchaException();
		}
		if (UserConstants.NOT_UNIQUE.equals(this.checkUserNameUnique(signupBody.getUsername()))) {
			throw new CustomException("该手机号已被注册", HttpStatus.CONFLICT);
		}
		SysUser user = new SysUser();
		Integer formatId = signupBody.getFormatId();
		if(ToolUtil.isNotEmpty(formatId)) {
			ZpFormat format = formatMapper.selectById(signupBody.getFormatId());
			if (ToolUtil.isEmpty(format)) {
				throw new CustomException("业态标签不存在", HttpStatus.CONFLICT);
			}
			// 标签
			user.setFormatId(format.getFormatId());
		}
		BeanUtil.copyProperties(signupBody, user);
		user.setUserName(signupBody.getUsername());
		user.setPassword(SecurityUtils.encryptPassword(signupBody.getPassword()));
		// 头像
		user.setAvatar(null);
		// 昵称
		user.setNickName("用户" + signupBody.getUsername().substring(signupBody.getUsername().length() - 6));
		// 手机号
		user.setPhonenumber(signupBody.getUsername());
		// 用户类型
		user.setUserType("11");
		this.insertUser(user);
	}

	@Override
	public void newforgot(NewForgot newForgot) {
		String code = newForgot.getCode();
		String verifyKey = Constants.CAPTCHA_CODE_KEY + newForgot.getUuid();
		String captcha = redisCache.getCacheObject(verifyKey);
		redisCache.deleteObject(verifyKey);
		if (captcha == null) {
			throw new CaptchaExpireException();
		}
		if (!StrUtil.equalsIgnoreCase(code, captcha)) {
			throw new CaptchaException();
		}
		SysUser user = this.selectUserByUserName(newForgot.getPhonenumber());
		if(ToolUtil.isEmpty(user)) {
			throw new CustomException("该手机未注册", HttpStatus.CONFLICT);
		}
		if(StrUtil.equals(user.getAvatar(), Constants.DEFAULT_AVATAR)) {
			user.setAvatar(null);
		}
		user.setPassword(SecurityUtils.encryptPassword(newForgot.getNewpassword()));
		this.updateById(user);
	}

	@Override
	public int updateUserInfo(UserInfoForm userInfo) {
		Long loginUserId = SecurityUtils.getLoginUserId();
		SysUser byId = this.getById(loginUserId);
		BeanUtil.copyProperties(userInfo, byId);
		String avatar = byId.getAvatar();
		if(StrUtil.equals(avatar, Constants.DEFAULT_AVATAR)) {
			byId.setAvatar(null);
		}
		int updateById = this.baseMapper.updateById(byId);
		return updateById;
	}

	@Override
	public int updateUserPwd(UserPwdForm userPwd) {
		String code = userPwd.getCode();
		String verifyKey = Constants.CAPTCHA_CODE_KEY + userPwd.getUuid();
		String captcha = redisCache.getCacheObject(verifyKey);
		redisCache.deleteObject(verifyKey);
		if (captcha == null) {
			throw new CaptchaExpireException();
		}
		if (!StrUtil.equalsIgnoreCase(code, captcha)) {
			throw new CaptchaException();
		}
		SysUser byId = this.getById(SecurityUtils.getLoginUserId());
		if(ToolUtil.isNotEmpty(byId)) {
			byId.setPassword(SecurityUtils.encryptPassword(userPwd.getNewPsw()));
			String avatar = byId.getAvatar();
			if(StrUtil.equals(avatar, Constants.DEFAULT_AVATAR)) {
				byId.setAvatar(null);
			}
			return this.baseMapper.updateById(byId);
		}
		return 0;
	}

	@Override
	public Page<SysUser> reclike(Page<SysUser> page, Long userId, String key) {
		QueryWrapper<SysUser> queryWrapper= new QueryWrapper<>();
		queryWrapper.eq("user_type", "11");
		if(StrUtil.isNotEmpty(key)) {
			queryWrapper.like("nick_name", key);
		}
		queryWrapper.ne("user_id", userId);
		queryWrapper.orderByDesc("create_time");
		return this.page(page, queryWrapper);
	}

}
